package edu.dali.enterprise_test.controller;

import com.github.pagehelper.PageHelper;
import edu.dali.enterprise_test.exception.UploadException;
import edu.dali.enterprise_test.kits.ExcelProc;
import edu.dali.enterprise_test.kits.PoiUtils;
import edu.dali.enterprise_test.model.Pager;
import edu.dali.enterprise_test.model.vo.Dto;
import edu.dali.enterprise_test.model.vo.SysRole;
import edu.dali.enterprise_test.model.vo.UserInfo;
import edu.dali.enterprise_test.service.product.ProductService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private HttpServletRequest request;

    @RequestMapping("index")
    public String index() {

        return "product/index";
    }

    @PostMapping("getData")
    @ResponseBody
    public Pager<Dto> getData(int page , int limit) {
        PageHelper.startPage(page,limit);

        UserInfo u = (UserInfo) SecurityUtils.getSubject().getPrincipal();
        List<SysRole> roles = u.getRoles();

        boolean superFlag = false;
        for (SysRole r:roles) {
            if (r.getRole().equals("super")) superFlag = true;
        }

        Dto dto = new Dto();


        String spmc = request.getParameter("spmc");
        String ggxh = request.getParameter("ggxh");
        String createtime = request.getParameter("createtime");

        if (!StringUtils.isEmpty(spmc)) dto.put("spmc" , spmc);
        if (!StringUtils.isEmpty(ggxh)) dto.put("ggxh" , ggxh);
        if (!StringUtils.isEmpty(createtime)) dto.put("createtime" , createtime);

        if (!superFlag) {
            dto.put("storeno" , u.getStoreno());
        }
        Pager p = productService.getData(dto);
        return p;
    }

    @RequestMapping("addDialog")
    public String addDialog() {
        return "product/dialog/add";
    }

    /**
     * 添加数据
     * @return
     */
    @PostMapping("add")
    @ResponseBody
    public Map<String ,Object> add(String spmc , String ggxh , String price , String stock , String spbm , String available) {
        Map<String , Object> map = new HashMap<>();
        Dto dto = new Dto();
        dto.put("spmc" , spmc);
        dto.put("ggxh" , ggxh);
        dto.put("price" , price);
        dto.put("stock" , stock);
        dto.put("spbm" , spbm);
        if (available.equals("on")) {
            dto.put("available" , 1);
        } else {
            dto.put("available" , 0);
        }

        productService.addProduct(dto);

        map.put("code" , 0);
        map.put("msg" , "添加商品成功");
        return map;
    }

    /**
     * 更新商品
     * @return
     */
    @RequestMapping("updateDialog/{id}")
    @RequiresRoles("super")
    public String updateDialog(@PathVariable String id , Model model) {
        model.addAttribute("id" , id);

        Dto dto = new Dto();
        dto.put("id" , id);
        Dto info = productService.getProductById(dto);
        model.addAttribute("info" , info);
        return "product/dialog/update";
    }

    /**
     * 更新数据
     * @return
     */
    @PostMapping("update")
    @ResponseBody
    @RequiresRoles("super")
    public Map<String , Object> update(String id , String spmc , String ggxh , String price , String stock , String spbm , String available) {
        Map<String , Object> map = new HashMap<>();
        Dto params = new Dto();
        params.put("id" , id);
        params.put("spmc" ,spmc);
        params.put("ggxh" ,ggxh);
        params.put("price" ,price);
        params.put("stock" ,stock);
        params.put("spbm" ,spbm);
        productService.updateProduct(params);
        map.put("code" , 0);
        map.put("msg" , "修改成功");
        return map;
    }

    /**
     * 删除数据
     * @param id 主键
     * @return
     */
    @PostMapping("delete")
    @ResponseBody
    @RequiresRoles("super")
    public Map<String , Object> delete(String id) {
        Map<String , Object> map = new HashMap<>();
        productService.deleteProduct(id);
        map.put("code" , 0);
        map.put("msg" , "删除成功");
        return map;
    }

    /**
     * 上传文件处理
     *
     * @return
     */
    @RequestMapping(value = "uploadProduct", method = RequestMethod.POST)
    @ResponseBody
    @RequiresRoles("super")
    public Map<String, Object> uploadProduct(@RequestParam MultipartFile file) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            InputStream fis = file.getInputStream();
            PoiUtils utils = new PoiUtils();
            String fileName = file.getOriginalFilename();
            String type = "";
            if (fileName.endsWith(".xlsx")) type="xlsx";
            else type = "xls";

            List<Map<String, String>> datas = utils.readExcelByFs(fis, type);
//            feeService.insertFee(datas);
            productService.insertProducts(datas);
            map.put("success", true);
            map.put("msg", "上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("msg", "上传失败:" + e.getMessage());
        } catch (UploadException e) {
            map.put("success" , false);
            map.put("msg" , "上传失败:" + e.getMessage());
        }
        return map;
    }

    @RequestMapping("download")
    public ResponseEntity<byte[]> download() throws IOException {
        List<Dto> list = productService.productList(null);

        ByteArrayOutputStream ret = ExcelProc.exportProduct(list);

        byte[] body = ret.toByteArray();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String timestamp = sdf.format(new Date());
            headers.add("Content-Disposition", "attchement;filename=" + new String(("商品明细"+timestamp).getBytes("utf-8"),"iso-8859-1")+".xlsx");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);

        return entity;
    }
}
